package com.eqdd.yiqidian.ui.mine.shenqing

import android.support.v7.widget.RecyclerView
import android.view.View
import com.bigkoo.pickerview.TimePickerView
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditHintBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimTimeSelectBean
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity
import com.eqdd.yiqidian.utils.SingleChooseUtil
import com.eqdd.yiqidian.utils.TimeUtil
import com.eqdd.yiqidian.widget.ActionSheetDialog
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import io.reactivex.Observable
import kotlinx.android.synthetic.main.activity_recyclerview.*
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

/**
 * 申请基础类
 * Created by jhj on 18-6-11.
 */
abstract class BaseApplyActivity : SlimBaseMultiEditActivity() {

    var isUpper: Boolean = false

    abstract val mTitle: String
    abstract val url: String
    abstract val isRequestLeader: Boolean
    open val leaderIndex: Int? = null

    var leader: String? = null
    val params = HttpParams()
    private var chooseDialog: ActionSheetDialog? = null

    override fun initBinding() {
        clearData()
        setContentView(R.layout.activity_recyclerview)
        initTopTitleBar(View.VISIBLE, mTitle)
        initTopRightText("提交", {
            if (checkParams()) {
                OkGo.post<HttpResult<*>>(url)
                        .params("companyId", user.companyId)
                        .params("userGuid", user.guid)
                        .params(uploadParams())
                        .execute(object : DialogCallBack<HttpResult<*>>(this) {
                            override fun onSuccess(response: Response<HttpResult<*>>) {
                                val httpResult = response.body()
                                if (httpResult.status == 200) {
                                    isSave = false
                                    setResult(Config.SUCCESS)
                                    finish()
                                }
                            }
                        })
            } else {
                toast(msg)
            }
        })
    }


    override fun initRecyclerView(): RecyclerView {
        return recyclerView
    }


    override fun setEditBeans() {
        datas.add(SlimEditHintBean("姓名", user.username, 0))
        datas.add(SlimEditHintBean("工号", user.jobNumber, 1))
        datas.add(SlimEditHintBean("部门", user.department, 2))
        datas.add(SlimEditHintBean("职位", user.post, 3))

        slimAdapterEx.register(R.layout.list_item_29, SlimInjector<SlimTimeSelectBean> { data, injector ->
            injector?.text(R.id.tv_left_content, data?.title)
                    ?.text(R.id.tv_right_content, data?.content)
                    ?.hint(R.id.tv_right_content, data?.hint)
        })
    }


    override fun loadNetData() {
        /**
         * 获取审批人
         */
        Observable
                .create<String?> {
                    OkGo.post<HttpResult<String>>(HttpConfig.BASE_URL + HttpConfig.GET_LEADER)
                            .params("userGuid", user.guid)
                            .params("companyId", user.companyId)
                            .execute(object : DialogCallBack<HttpResult<String>>(this) {
                                override fun onSuccess(response: Response<HttpResult<String>>) {
                                    val httpResult = response.body()
                                    if (httpResult.status == 200) {
                                        httpResult.items?.let { s ->
                                            it.onNext(s)
                                        }
                                    }
                                }
                            })

                }
                .subscribe {
                    this.leader = it
                    leaderIndex?.let { index ->
                        if (leaderIndex != null) {
                            if (it.isNullOrBlank()) {
                                slimAdapterEx.data.removeAt(index)
                                slimAdapterEx.notifyItemRemoved(index)
                            } else {
                                slimAdapterEx.getDataItem(index).content = it
                                slimAdapterEx.notifyItemChanged(index)
                            }
                        }
                    }

                }

    }

    override fun checkParams(): Boolean {
        if (isRequestLeader && (leader == null || "" == leader)) {
            msg = "无审核人,请联系管理员"
            return false
        }
        return super.checkParams()
    }


    private fun parseDate(time: String?): Date? {
        if (time.isNullOrBlank()) {
            return null
        }
        val sf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)
        return sf.parse(time)
    }

    fun openTimePicker(startIndex: Int, endIndex: Int, isCalculate: Boolean = false) {
        val now = Calendar.getInstance()
        val sf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)
        var upDate: Date? = parseDate(slimAdapterEx.getDataItem(startIndex).content)
        var downDate: Date? = parseDate(slimAdapterEx.getDataItem(endIndex).content)
        if (isUpper) {
            now.time = upDate ?: Date()
        } else {
            now.time = downDate ?: Date()
        }
        TimePickerView
                .Builder(this, TimePickerView.OnTimeSelectListener { date, v ->
                    if (isUpper) {
                        if (downDate != null && date.after(downDate)) {
                            toast("开始时间小于结束事件，请重新选择")
                            return@OnTimeSelectListener
                        }
                        upDate = date
                        slimAdapterEx.getDataItem(startIndex).content = sf.format(date)
                        slimAdapterEx.notifyItemChanged(startIndex)
                    } else {
                        if (upDate != null && date.before(upDate)) {
                            toast("开始时间小于结束事件，请重新选择")
                            return@OnTimeSelectListener
                        }
                        downDate = date
                        slimAdapterEx.getDataItem(endIndex).content = sf.format(date)
                        slimAdapterEx.notifyItemChanged(endIndex)
                    }
                    if (upDate != null && downDate != null && isCalculate) {
                        val time = TimeUtil.calculateDate(upDate, downDate)
                        datas[endIndex + 1].content = time
                        slimAdapterEx.notifyItemChanged(endIndex + 1)
                    }

                })
                .setOutSideCancelable(true)
                .setType(booleanArrayOf(true, true, true, true, true, false))
                .setDate(now)
                .build()
                .show()
    }

    fun bottomDialog(clickIndex: Int,requestCode: Int){
        if (chooseDialog == null) {
            SingleChooseUtil.getChooseDialog(this, requestCode, { sheet ->
                chooseDialog = sheet
                sheet.show()
            }) { position, strings ->
                slimAdapterEx.getDataItem(clickIndex).content = strings[position - 1]
                slimAdapterEx.notifyItemChanged(clickIndex)
            }
        } else {
            chooseDialog?.show()
        }
    }


    abstract fun uploadParams(): HttpParams

}